# Private Message bot
# by Cee Pee

import os
import random
import re
import forumapi

def find_phrases():
	"""Returns all phrases files."""
	
	phrases = []
	for file in os.listdir("data"):
		m = re.match("^(.*)\.phrases$", file)
		if m:
			phrases.append(m.group(1))
	
	return(phrases)

def settings(settings):
	settings.add_option("--phrases", type="choice", choices=find_phrases(), help="phrases file", metavar="FILE")
	settings.add_option("-m", "--pm", type="int", help="private message ID to respond to", metavar="ID")
	settings.add_option("-u", "--users", type="list", help="users to send the message to", metavar="IDS")
	settings.add_option("--bcc", type="list", help="users to send a blind carbon copy to", metavar="IDS")
	settings.add_option("--reply", type="bool", default=True, reverse={"opt_str": "--forward", "help": "forward the message"}, help="reply to the message")
	settings.add_arg("title", optional=True, help="title to use")
	settings.add_arg("text", optional=True, default="PM content", help="text to post")

def main(me, options, args):
	if options.phrases:
		phrases = open(forumapi.data_file(options.phrases, "phrases"), encoding="utf8").read().split("\n")
	else:
		phrases = []
	
	if phrases:
		phrase = random.choice(phrases)
	else:
		phrase = args.text
	
	print("Message: " + phrase)
	
	users = [forumapi.User(me, id=int(user)) for user in options.users]
	
	if options.pm:
		pm = me.module.get_attr("PrivateMessage").PrivateMessage(me, id=pm)
		print(repr(pm.reply(phrase, title=args.title, users=users, bcc=options.bcc, forward=options.forward)))
	else:
		prepared_pm = me.module.get_attr("PrivateMessage").prepare_pm(me, users=users, bcc=options.bcc)
		if args.title:
			prepared_pm.title = args.title
		
		prepared_pm.message = phrase
		
		print(repr(prepared_pm.submit()))

if __name__ == "__main__":
	forumapi.run(main, options=settings, supported_types=["vbulletin"])
